package com.example.adminLite.admin.controller;

import com.example.adminLite.exception.WebRunException;
import com.example.adminLite.model.Music;
import com.example.adminLite.model.MusicType;
import com.example.adminLite.service.MusicService;
import com.example.adminLite.service.MusicTypeService;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.servlet.ModelAndView;

import java.util.List;

@Controller
@RequestMapping("admin/music")
public class MusicController {

    private final MusicService MusicService;
    private final MusicTypeService musicTypeService;

    public MusicController(MusicService MusicService, MusicTypeService musicTypeService) {
        this.MusicService = MusicService;
        this.musicTypeService = musicTypeService;

    }

    @GetMapping("add")
    public ModelAndView add(
            @RequestParam(required = false, defaultValue = "") String  errorMessage,
            ModelAndView modelAndView
    ) {
        List<MusicType> musicTypeList = this.musicTypeService.index();
        modelAndView.addObject("errorMessage", errorMessage);
        modelAndView.addObject("musicTypeList", musicTypeList);
        modelAndView.setViewName("/admin/music/add");
        return modelAndView;
    }

    @GetMapping("index")
    public ModelAndView  index(ModelAndView modelAndView) {
        List<Music> musicList = this.MusicService.index();
        modelAndView.addObject("musicList", musicList);
        modelAndView.setViewName("/admin/music/index");
        // System.out.println(MusicList);
        return modelAndView;
    }

    @GetMapping("edit")
    public ModelAndView edit(
            @RequestParam long id,
            ModelAndView modelAndView
    ) {
        Music Music = this.MusicService.findById(id);
        modelAndView.addObject("music", Music);
        modelAndView.setViewName("/admin/music/edit");
        return modelAndView;
    }

    @PostMapping("save")
    public String save(
            @RequestParam(required = false, defaultValue = "0") long id,
            @RequestParam String musicName,
            @RequestParam long musicTypeId
    ) {
        Music music = new Music();
        if (id != 0){
            music.setId(id);
        }
        music.setMusicName(musicName);
        music.setMusicTypeId(musicTypeId);
        this.MusicService.save(music);

        return "redirect:/admin/music/index";
    }

    @GetMapping("del")
    public String del(
            @RequestParam long id
    ) {
        this.MusicService.del(id);
        return "redirect:/admin/music/index";
    }


}
